package cn.vshare.Realm;

import cn.vshare.entity.PermissionSecond;
import cn.vshare.entity.Role;
import cn.vshare.entity.User;
import cn.vshare.service.PermissionSecondService;
import cn.vshare.service.RoleService;
import cn.vshare.service.UserService;
import cn.vshare.util.JSON2Console;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionSecondService permissionSecondService;


    //添加角色信息
    public void addRole(User user,SimpleAuthorizationInfo info){
        //获取用户的角色信息
        //User user1=userService.login(user);
        //存储用户的角色信息
        info.addRole(user.getRole().getName());
        System.out.println("=====111==========");
        JSON2Console.output2Cnsole(info);
    }

    //添加权限信息
    public SimpleAuthorizationInfo addPermissionSecond(Role role, SimpleAuthorizationInfo info){
        Map<String,Object>map=new HashMap<>();
        //获取用户的权限信息
        map.put("r_id",role.getId());
        Role role1=roleService.queryPermissionSecond2Role(map);
        //存储权限信息
        Set<PermissionSecond>permissionSecondSet=role1.getPermissionSecondHashSet();
        Iterator<PermissionSecond>iterator=permissionSecondSet.iterator();
        while (iterator.hasNext()){
            PermissionSecond permissionSecond=iterator.next();
            info.addStringPermission(permissionSecond.getName());
        }
        System.out.println("=====222==========");
        JSON2Console.output2Cnsole(info);
        return info;

    }


    //获取授权信息,查看是否具有相关的权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user= (User) SecurityUtils.getSubject().getSession().getAttribute("USER");
        //User user= (User) principalCollection.getPrimaryPrincipal();//无法使用
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        //添加角色信息
        addRole(user,info);
        //添加权限信息
        info= addPermissionSecond(user.getRole(),info);
        System.out.println("=====333=========");
        JSON2Console.output2Cnsole(info);
        return info;
    }


    //对用户进行认证,验证身份
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        String userName=usernamePasswordToken.getUsername().trim();
        String userPassword="";
        if (usernamePasswordToken.getPassword()!=null){
            userPassword=new String(usernamePasswordToken.getPassword());
        }

        //查询数据库的用户信息
        User user=userService.login(new User(userName,userPassword));
        if (user!=null){
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getNickName(),user.getPassword(),getName());
            System.out.println("=====444==========");
            JSON2Console.output2Cnsole(info);
            JSON2Console.output2Cnsole(user);
            //将当前用户设置到Session中去以便获取当前用户信息
            this.setSession("USER",user);
            return info;
        }
        return null;
    }


    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(Object key,Object value){
        Subject currSubject=SecurityUtils.getSubject();

        if (null!=currSubject){
            Session session=currSubject.getSession();
            System.out.println("当前session默认存储时间:[ "+session.getTimeout()+" ]毫秒");
            if (null!=session){
                session.setAttribute(key,value);
            }
        }
    }

}
